<?php
/**
 * Slipstream :: Highly adaptive dependency injection framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Slipstream\Infrastructure\Context;

use Slipstream\Configuration\AbstractPolicy;
use Slipstream\Configuration\ContextInterface;
use Slipstream\Configuration\PolicyInterface;
use Slipstream\Configuration\PolicyScope;

/**
 * Default implementation of ScopeAnalyzerInterface
 * 
 * <b>Behavior notes:</b>
 * <ul>
 *   <li>Policies bound to the root context will <b>always</b> be in scope</li>
 *   <li>Policies that do not extend <i>AbstractPolicy</i> will be <b>discarded</b></li>
 *   <li>Policies with the <i>Reference</i> scope will be <b>discarded</b></li>
 * </ul>
 * 
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class ScopeAnalyzer extends AbstractScopeAnalyzer
{
	/**
	 * Returns true if a policy is in the scope of a target context
	 * 
	 * @throws LogicException If target context is not set
	 * @param PolicyInterface $policy
	 * @param ContextInterface $context Context the policy is bound to
	 * @return bool
	 */
	public function isInScope(PolicyInterface $policy, ContextInterface $context)
	{
		if(!($policy instanceof AbstractPolicy)) {
			return false;
		} elseif(is_null($context->getParentContext())) {
			return true;
		}
		
		switch($policy->get(AbstractPolicy::OPTION_SCOPE)) {
			case PolicyScope::All:
				return true;
				
			case PolicyScope::InheritBySiblings:
				if($context->getParentContext() !== $this->targetContext->getParentContext()) {
					return false;
				}
			
			case PolicyScope::InheritByChildren:
				return ($this->relevanceAnalyzer->getWeight($context, $this->targetContext) !== 0);
			
			case PolicyScope::Local:
				return ($context === $this->targetContext);
				
			case PolicyScope::Reference:
				return false;
		}
		return false;
	}
}